from PIL import Image, ImageDraw, ImageFont, ExifTags
from random import randint 
from time import sleep
import threading
import os, sys
import time
try:
    import exifread
except:
    os.system("pip install exifread")
    import exifread

global threads_count
threads_count = 0

def getPhotoTime(filename):

    state = os.stat(filename)
    dateStr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(state[-2]))
    data = exifread.process_file( open(filename, 'rb') )

    if data:
        try:
            dateStr = str(data['EXIF DateTimeOriginal']).replace(":","-")[:10] + str(t)[10:]
        except:
            pass

    return dateStr

def add_watermark(filename, fontPath):

    global threads_count
    outdir= 'watermark/'
    image = Image.open(filename)
    draw = ImageDraw.Draw(image)
    fillcolor= '#FFFF00'
    width, height = image.size
    if width < height:
        font = ImageFont.truetype(fontPath, int(0.05*width))
        d_width, d_height=width-0.05*width*10, 0.95*height - 0.05*width       
    else:
        font = ImageFont.truetype(fontPath, int(0.05*height))
        d_width, d_height=width-0.05*height*10, 0.90*height
    draw.text((d_width, d_height), getPhotoTime(filename), font=font, fill=fillcolor)

    new_filename= filename
    image.save(outdir + new_filename, quality=100)
    threads_count -= 1

def main(startdir, fontPath):

    global threads_count
    threads = []
    os.chdir(os.path.abspath(startdir))
    outdir= 'watermark/'
    if not os.path.exists(outdir): os.mkdir(outdir)
    for obj in os.listdir():
        if obj[-4:] in ['.jpg', 'jpeg', '.png', '.bmp']:
            threads.append(threading.Thread(target=add_watermark,args=(obj, fontPath)))

    if sys.maxsize>2**32:
        for t in threads:
            t.start()
    else:
        for t in threads:
            while threads_count >= 10:
                sleep(randint(1,2)/100)
            t.start()
            threads_count += 1


if __name__ == "__main__":
    if not len(sys.argv) <3:
        if sys.argv[2][-4:].strip('\'\"\\').rstrip("/").lower() == '.ttf': 
            fontPath = os.path.abspath(sys.argv[2])
            main(sys.argv[1], fontPath)
        elif sys.argv[1][-4:].strip('\'\"\\').rstrip("/").lower() == '.ttf':
            fontPath = os.path.abspath(sys.argv[1])
            main(sys.argv[2], fontPath)
        else:
            print(sys.argv[1][:4].strip('\'\"\\').rstrip("/").lower(), sys.argv[2][:4].strip('\'\"\\').rstrip("/").lower())
    else:
        print("\tTo add watermark into pictures,")
        print("\tUse the tool via:")
        print("\tpython [this_tool] [dir] [TTFfontPath]")
